﻿Function Disable-EventGroup
{
  [CmdletBinding(DefaultParameterSetName="Number")]
  param
  (
    [parameter(Position=0,
               Mandatory=$True,
               ParameterSetName="Number")]
    [int]
    $Number = -1,

    [parameter(Position=0,
               Mandatory=$True,
               ParameterSetName="FriendlyName")]
    [String]
    $FriendlyName,

    [parameter(Position=0,
               Mandatory=$True,
               ParameterSetName="Order")]
    [int]
    $Order = -1,

    [parameter(Position=0,
               Mandatory=$True,
               ParameterSetName="Id")]
    [System.Guid]
    $Id
  )

  Begin
  {
    # Lock the group list XML file while editing the event group.
    $Created = $False
    $Script:GroupMutex = New-Object System.Threading.Mutex($True,"eventlib_write_group_xml",[ref]$Created)

    if ($Created -eq $False)
    {
      try `
      {
        $Lock = $Script:GroupMutex.WaitOne(2000)
      }
      catch [System.Threading.AbandonedMutexException] `
      {
        Write-Warning "Caught AbandonedMutexException.  Consider checking the Event Group list for consistency."
      }
    }
    else
    {
      $Lock = $True
    }

    if ($Lock -eq $False)
    {
      $Exception = New-Object System.TimeoutException "Timed out waiting to lock the eventlib_write_group_xml mutex."
      throw $Exception
    }
  }

  Process
  {
    $GroupList = $(Get-EventGroup)

    if ($GroupList -eq $Null)
    {
      $GroupList = @()
    }
    elseif ($GroupList -isnot [system.array])
    {
      $GroupList = @($GroupList)
    }


    # Find the group we're modifying.
    if ($Number -ge 0)
    {
      $ToSet = Get-EventGroup -Number $Number
    }
    elseif ($FriendlyName.Length -gt 0)
    {
      $ToSet = Get-EventGroup -FriendlyName $FriendlyName
    }
    elseif ($Id -ne $Null)
    {
      $ToSet = Get-EventGroup -Id $Id
    }
    elseif ($Order -ge 0)
    {
      $ToSet = Get-EventGroup -Order $Order
    }

    # If only one group remains, it's the one we're disabling.
    if ($ToSet.Count -eq 1)
    {
      $ToSetIndex = $([array]::IndexOf($GroupList,$ToSet))
      $ToSet.IsEnabled = $False

      $GroupList[$ToSetIndex] = $ToSet
      Export-Clixml -Path $(Join-Path $Script:ModulePath "Data\groups.xml") -InputObject $GroupList

    }
    else
    {
      $Exception = New-Object System.ArgumentException "Fatal error.  $($ToSet.Count) groups matched the given parameters.  Check the group XML file."
      throw $Exception
    }
  }

  End
  {
    $Script:GroupMutex.ReleaseMutex()
  }
}